<template>
  <div id="app">
<!--    <router-view v-wechat-title="$route.meta.title"></router-view>-->
    <keep-alive>
      <router-view v-wechat-title="$route.meta.title" v-if="$route.meta.keepAlive">
        <!-- 这里是会被缓存的视图组件，比如列表A页面 -->
      </router-view>
    </keep-alive>

    <router-view v-wechat-title="$route.meta.title" v-if="!$route.meta.keepAlive">
      <!-- 这里是不被缓存的视图组件，比如详情B页面-->
    </router-view>

    <van-overlay :show="loadingOverlayVisible">
      <div class="loading-overlay-wrapper">
        <van-loading type="spinner" />
      </div>
    </van-overlay>

    <van-overlay :show="subscribeOverlayVisible">
      <div class="flex flex-col flex-center recharge-wrapper" style="height: 100%;">
        <div class="pd20 round-box bg-color-white">
          <div class="text-center">
            {{APP_NAME}}
          </div>

          <div class="text-center mt10">
            <img :src="mpQrcode" height="200" width="200" v-if="mpQrcode" />
          </div>

          <div class="text-center mt5 font-big">
            长按二维码关注公众号
          </div>
        </div>

        <div class="flex flex-row flex-center pd20">
          <i class="iconfont icon-guanbi" style="font-size: 34px; color: #FFFFFF;"
             @click="subscribeOverlayVisible=false"/>
        </div>
      </div>
    </van-overlay>

    <remote-js :src="STATIC_BASE_URL + 'js/socket.io.js'" @load="onSocketIoJsLoaded"></remote-js>
  </div>
</template>

<script>
  import {siteConfigUri, STATIC_BASE_URL, WS_HOST, userLoginByOpenidUri, userLoginByTokenUri} from './common/api';
  import Vue from 'vue';
  import {Overlay, Loading, Toast} from 'vant';
  import util from "./assets/js/util";
  Vue.use(Overlay).use(Loading).use(Toast);

  let uuid = '';
  let socketIoJsLoaded = false;
  let wsConnecting = false;

  export default {
    name: 'app',
    data() {
      return {
        STATIC_BASE_URL: STATIC_BASE_URL,
        APP_NAME: APP_NAME,
        loadingOverlayVisible: true,
        subscribeOverlayVisible: false,
        mpQrcode: ''
      }
    },
    methods: {
      onSocketIoJsLoaded() {
        socketIoJsLoaded = true;
        this.initSocketIo();
      },
      initSocketIo() {
        if(wsConnecting || !socketIoJsLoaded || uuid.length == 0 || this.GLOBAL.ws.connected) {
          return;
        }
        wsConnecting = true;
        const that = this;
        // 连接服务端
        const socket = io(WS_HOST + ':2120');
        // 连接后登录
        socket.on('connect', function() {
          socket.emit('login', uuid);
          that.GLOBAL.ws.connected = true;
          console.log('ws connect');
        });
        socket.on('disconnect', function () {
          that.GLOBAL.ws.connected = false;
          console.log('ws disconnect');
        });
        // 后端推送来消息时
        socket.on('new_msg', function(message) {
          console.log("new_msg:" + message);
          that.EventBus.$emit('OnMessageReceived', message);
        });
        wsConnecting = false;
      },
      showSubscribeOverlay() {
        const that = this;
        const openid = window.localStorage.getItem('openid');
        if(that.GLOBAL.siteConfig && (openid == null || (that.GLOBAL.userInfo && !that.GLOBAL.userInfo.subscribe))) {
          if(that.GLOBAL.siteConfig.mp_qrcode) {
            that.mpQrcode = that.GLOBAL.siteConfig.mp_qrcode;
          } else {
            that.mpQrcode = STATIC_BASE_URL + 'images/mp/qrcode.jpg';
          }
          that.subscribeOverlayVisible = true;
        }
      },
      loginByToken() {
        const access_token = window.localStorage.getItem('access_token');
        if(!access_token) {
          return;
        }
        const that = this;
        this.$http.get(userLoginByTokenUri + '?access_token=' + access_token).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            // that.toast.fail(msg);
          } else {
            that.EventBus.$emit('OnUserLogined', {user: data.user, member: data.member, method: 'loginByToken'});
            that.showSubscribeOverlay();
          }
        }, response => {
          // error callback
        })
      },
      loginByOpenid() {
        const openid = window.localStorage.getItem('openid');
        if(openid) {
          const that = this;
          this.$http.get(userLoginByOpenidUri + '?openid=' + openid).then(response => {
            let {code, msg, data} = response.body
            if (code != 0) {
              // that.toast.fail(msg);
            } else {
              that.EventBus.$emit('OnUserLogined', {user: data.user, member: data.member, method: 'loginByOpenid'});
              that.showSubscribeOverlay();
            }
          }, response => {
            // error callback
          })
        } else {
          // if(!window.sessionStorage.getItem('wx_auth')) {
          //   const rUrl = window.location.protocol + '//' + window.location.host + this.$router.history.base + '/user/redirect';
          //   const href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+WECHAT_APP_API+'&redirect_uri='+encodeURIComponent(rUrl)+'&response_type=code&scope=snsapi_base&state=#wechat_redirect';
          //   window.location.href = href;
          // }
        }
      },
      getSiteConfig() {
        const that = this;
        this.$http.get(siteConfigUri).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            alert(msg);
          } else {
            that.GLOBAL.siteConfig = data.cfg;
            that.EventBus.$emit('OnSiteConfigLoaded', null);
            that.showSubscribeOverlay();
          }
        }, response => {
          // error callback
        })
      }
    },
    beforeCreate: function () {
//      console.log('App beforeCreate 钩子执行...')
    },
    created: function () {
//      console.log('App created 钩子执行...')
      const that = this;
      const fromuid = util.getQueryVariable('fromuid');
      if(fromuid) {
        localStorage.setItem('fromuid', fromuid);
      }
      this.getSiteConfig();

      this.EventBus.$on('OnUserLogined', (data) => {
        if(data && data.user) {
          uuid = data.user.gomessage_uid;
          window.localStorage.setItem('openid', data.user.openid);
          if(data.method != 'loginByToken') {
            window.localStorage.setItem('access_token', data.user.access_token);
          }
          window.localStorage.setItem('upload_token', data.user.upload_token);
          window.localStorage.setItem('user_id', data.user.id);
          this.GLOBAL.userInfo = data.user;
          this.GLOBAL.memberProfile = data.member;
          this.initSocketIo();
        }
      });

      this.EventBus.$on('OnUserLogout', (data) => {
        window.localStorage.removeItem('openid');
        window.localStorage.removeItem('access_token');
        window.localStorage.removeItem('upload_token');
        window.localStorage.removeItem('user_id');
        this.GLOBAL.userInfo = null;
        this.GLOBAL.memberProfile = null;
      });

      this.EventBus.$on('OnConnectToGoEasy', () => {
        this.initSocketIo();
      });

      if(isWxServiceEnable) {
        if(this.$route.name != 'UserLogin' && this.$route.name != 'UserRegister' && this.$route.name != 'UserRedirect') {
          this.loginByOpenid();
        }
      } else {
        this.loginByToken();
      }
    },
    beforeMount: function () {
//      console.log('App beforeMount 钩子执行...')
    },
    mounted: function () {
      this.loadingOverlayVisible = false;
      // this.login();
//      console.log('App mounted 钩子执行...')
    },
    beforeUpdate: function () {
//      console.log('App beforeUpdate 钩子执行...')
    },
    updated: function () {
//      console.log('App updated 钩子执行...')
    },
    beforeDestroy: function () {
//      console.log('App beforeDestroy 钩子执行...')
      const that = this;

    },
    destroyed: function () {
//      console.log('App destroyed 钩子执行...')
    }
  }
</script>

<style>
  html, body, #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    color: #2c3e50;
    font-size: 16px;
    height: 100%;
  }

  .loading-overlay-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
</style>
